﻿using RndMaterialDisposalService.Controllers.SmallBatchTrial;
using RndMaterialDisposalService.Helper;
using RndMaterialDisposalService.Models.RequestModel;
using RndMaterialDisposalService.Models.ResponseModel;
using RndMaterialDisposalService.Services.Interface.OutsourcingProcessing;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using RndMaterialDisposalService.Models.RequestModel;
using RndMaterialDisposalService.Attrbutes;
using RndMaterialDisposalService.Models;
using RndMaterialDisposalService.Services.Interface.SmallBatchTrial;
using RndMaterialDisposalService.Services.Interface.TemporaryDocument;
using Ganss.Excel;
using RndMaterialDisposalService.Services.TemporaryDocumentService;
using ValidationProblemTracking.Services.Interface.ValidationProblemTracking;
using ValidationProblemTracking.Models;
using NPOI.SS.Formula.Functions;

namespace RndMaterialDisposalService.Controllers.ValidationProblemTracking
{
    /// <summary>
    /// 中试验证问题处理电子流
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class ValidationProblemController : ControllerBase
    {
        private ILogger<ValidationProblemController> logger;
        private readonly string ProcessFullName = "ValidationProblemTracking\\ValidationProblem";
        private IValidationProblemService iValidationProblemService;
        private IConfiguration configuration;
        private readonly string SaveFormDataUrl = "/api/WorkflowData/ApplicationData";
        private readonly string ProcessFolioUrl = "/api/WorkflowData/ApplicationNumber";

        public ValidationProblemController(ILogger<ValidationProblemController> _logger,
            IValidationProblemService _iValidationProblemService,
            IConfiguration _configuration) 
        {
            logger = _logger;
            iValidationProblemService = _iValidationProblemService;
            configuration = _configuration;
        }

        /// <summary>
        /// 获取表单数据
        /// </summary>
        /// <param name="procInstID">流程实例编号</param>
        /// <param name="applicationNumber"></param>
        /// <returns></returns>
        [HttpGet("GetFormData")]
        public async Task<IActionResult> GetFormData(string? procInstID, string? applicationNumber)
        {
            var CommonServiceHost = configuration.GetSection("CommonServiceHost").Value;
            var result = new FormInfoResp();
            if (!string.IsNullOrWhiteSpace(procInstID))
            {
                var url = $"{CommonServiceHost}{SaveFormDataUrl}?procInstID={procInstID}";
                result = await HttpHelper.GetAsync<FormInfoResp>(url);
                result.ViewsStatus = "Approval";
                return Ok(result);
            }

            var formDataModel = new ValidationProblemFlowReq();
            var url2 = $"{CommonServiceHost}{ProcessFolioUrl}?workflowCode={ProcessFullName}";
            var appNumber = await HttpHelper.GetAsync<string>(url2);
            result.ApplicationNumber = appNumber;
            result.ViewsStatus = "Start";
            result.FormData = JsonConvert.SerializeObject(formDataModel);
            return Ok(result);
        }

        /// <summary>
        /// 返回中试验证问题处理电子流报表主数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("ValidationProblemReportFormData")]
        [PageList]
        public IActionResult ValidationProblemReportFormData(ValidationProblemReportConditionModel input)
        {
            var list = iValidationProblemService.GetValidationProblemReportFormPageList(input);
            int count = iValidationProblemService.GetValidationProblemReportFormData(input).Count();

            var result = ApiResponsePageList<ValidationProblemReportFormModel>.CreatePageListByResult(list, input.PageIndex, input.PageSize, count);

            return Ok(result);
        }

        /// <summary>
        /// 新增报表数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("SavaValidationProblemReportFormData")]
        public async Task<IActionResult> SavaValidationProblemReportFormData(ValidationProblemBusinessDataModel input)
        {
            int count = 0;
            string _ProcInstId = input.ProcInstId ?? "0";
            try
            {
                if (input != null)
                {
                    input.SysId = Guid.NewGuid();
                    count = await iValidationProblemService.AddValidationProblemBusinessData(input);
                }
                logger.LogInformation($"新增报表数据（中试验证问题处理电子流）,流程实例号：{_ProcInstId},数量：{count},时间：{DateTime.Now}");
                return Ok(count);
            }
            catch (Exception ex)
            {
                logger.LogInformation($"新增报表数据（中试验证问题处理电子流）,流程实例号：{_ProcInstId},异常原因：{ex.ToString()},时间：{DateTime.Now}");
                throw;
            }
        }

        /// <summary>
        /// 文件下载
        /// </summary>
        /// <param name="relativePath"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        [HttpGet("DownloadFile")]
        [PageList]
        public async Task<IActionResult> DownloadFile(string relativePath, string fileName)
        {
            var fileDir = configuration.GetValue<string>("FileUploadPath");
            var fileFullPath = $"{fileDir}\\{relativePath}";
            var stream = await System.IO.File.ReadAllBytesAsync(fileFullPath);
            return File(stream, "application/octet-stream", fileName);
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="inputCondition"></param>
        /// <returns></returns>
        [HttpPost("ValidationProblemReportExport")]
        [PageList]
        public async Task<IActionResult> ValidationProblemReportExport(ValidationProblemReportConditionModel inputCondition)
        {
            inputCondition.PageIndex = 1;
            inputCondition.PageSize = 65535;
            var list = iValidationProblemService.GetValidationProblemReportFormData(inputCondition);
            var fileDir = configuration.GetValue<string>("FileUploadPath");
            if (!System.IO.Directory.Exists($"{fileDir}\\Report"))
            {
                Directory.CreateDirectory($"{fileDir}\\Report");
            }
            var filePath = $"Report\\中试验证问题处理电子流{Guid.NewGuid().ToString("N")}.xlsx";
            await new ExcelMapper().SaveAsync($"{fileDir}\\{filePath}", list);
            return Ok(filePath);
        }

        /// <summary>
        /// 获取启动单数据
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        [HttpPost("GetLaunchOrderDataList")]
        [PageList]
        public IActionResult GetLaunchOrderDataList(LaunchOrderConditionModel input)
        {
            var data = iValidationProblemService.GetLaunchOrderDataList(input);

            var result = ApiResponsePageList<LaunchOrderModel>.CreatePageListByResult(data.Item1, input.PageIndex, input.PageSize, data.Item2);

            return Ok(result);
        }

        /// <summary>
        /// 根据ProcInstId获取启动单数据
        /// </summary>
        /// <param name="procInstId"></param>
        /// <returns></returns>
        [HttpGet("GetProcInstIdLaunchOrderDataList")]
        public IActionResult GetProcInstIdLaunchOrderDataList(string procInstId)
        {
            var data = iValidationProblemService.GetProcInstIdLaunchOrderDataList(procInstId);

            return Ok(data);
        }


        /// <summary>
        /// 邮件知会
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost("SendEmailNotification")]
        public IActionResult SendEmailNotification(InformInformation info) 
        {
            try
            {
                var state =  iValidationProblemService.SendEmailNotification(info);
                logger.LogInformation($"邮件知会（中试验证问题处理电子流）,流程实例号：{info.ProcInstId},标题：{info.Subject},时间：{DateTime.Now}");
                return Ok(state);
            }
            catch (Exception ex)
            {
                logger.LogInformation($"邮件知会（中试验证问题处理电子流）,流程实例号：{info.ProcInstId},异常原因：{ex.ToString()},时间：{DateTime.Now}");
                throw;
            }
        }
    }
}
